package com.heartunderblade.rpc.loadbalancer;

import cn.hutool.core.util.RandomUtil;
import com.heartunderblade.rpc.RpcPojo.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.Random;

public class RandomLoadBalancer implements LoadBalancer {
    /**
     * 随机轮询
     * @param requestParams       请求参数
     * @param serviceMetaInfoList 可用服务列表
     * @return
     */
    private final Random random = new Random();

    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        int size = serviceMetaInfoList.size();
        if (size == 0) {
            return null;
        }
        // 只有 1 个服务，不用随机
        if (size == 1) {
            return serviceMetaInfoList.get(0);
        }
        int currentIndex = random.nextInt(size);
        return serviceMetaInfoList.get(currentIndex);
    }
}
